package com.newlink.building.common_base.widget

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.widget.ImageView
import android.widget.TextView
import com.newlink.building.common_base.R
import org.jetbrains.anko.backgroundResource
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit


/**
 * Created by xiaodong on 2022/9/15.
 */
class ToastSettingDialog(builder: Builder) : Dialog(builder.context, R.style.toast_setting_dialog) {
    private var mTitleText = ""
    private var mMessageText = ""
    private var mDrawableId = 0 /*R.drawable.toast_success_green*/
    private val executor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
    private val duration: Long = 2000L
    private var scheduledFuture: ScheduledFuture<*>? = null

    init {
        initView(builder)
    }

    private fun initView(builder: Builder) {
        mTitleText = builder.tittle
        mMessageText = builder.message
        mDrawableId =
            if (builder.drawableId > 0) builder.drawableId else R.drawable.toast_success_green
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.setGravity(Gravity.CENTER)
        setContentView(R.layout.toast_settings_dialog)
        (findViewById<TextView>(R.id.tv_title)).text = mTitleText
        (findViewById<TextView>(R.id.tv_message)).text = mMessageText
        (findViewById<ImageView>(R.id.iv_success)).backgroundResource = mDrawableId
    }

    class Builder(internal val context: Context) {
        internal var tittle: String = ""
        internal var message: String = ""
        internal var drawableId: Int = 0

        fun tittle(tittle: String): Builder {
            this.tittle = tittle
            return this
        }

        fun message(message: String): Builder {
            this.message = message
            return this
        }

        fun drawable(drawableId: Int): Builder {
            this.drawableId = drawableId
            return this
        }

        fun build(): ToastSettingDialog {
            return ToastSettingDialog(this)
        }
    }

    override fun show() {
        super.show()
        val runner = Runnable { dismiss() }
        scheduledFuture = executor.schedule(runner, duration, TimeUnit.MILLISECONDS);
    }

    fun clearTask() {
        dismiss()
        scheduledFuture?.cancel(true)
        executor.shutdown()
    }
}